import request from '@/utils/request'
import * as qs from 'qs'

export class ManagerForm {
  birth;
  cityId;
  company;
  job;
  password;
  phone;
  realName;
  sex;
}

export var ManagerFormRule = {
  birth: [
    {type: 'date', required: true, message: '必填'}
  ],
  cityId: [
    {type: 'number', required: true, message: '必填'}
  ],
  company: [
    {required: true, message: '必填'}
  ],
  job: [
    {required: true, message: '必填'}
  ],
  phone: [
    {required: true, message: '必填'},
    {pattern: /^1\d{10}$/, message: '手机号格式错误。例如：18812345678'}
  ],
  realName: [
    {required: true, message: '必填'},
    {min: 2, max: 20, message: '请填写正确的姓名'}
  ],
  sex: [
    {required: true, message: '必填'}
  ]
}

export function addRootAccount(form) {
  return request.post('/api/sysAdmin/manager/addRoot', form)
    .then(json => {
      if (json.result) {
        return json.data
      } else {
        throw new Error(json.message)
      }
    })
}

export function deleteRootAccount(id) {
  return request.delete(`/api/sysAdmin/manager/${id}`)
    .then(json => {
      if (json.result) {
        return json.data
      } else {
        throw new Error(json.message)
      }
    })
}

export function updateRootAccount(form) {
  return request(`/api/sysAdmin/manager/${form.id}`, form)
    .then(json => {
      if (json.result) {
        return json.data
      } else {
        throw new Error(json.message)
      }
    })
}

export function getProfile() {
  return request.get('/api/sys/manager/profile')
    .then(json => {
      if (json.result) {
        return json.data
      } else {
        return new Error(json.message)
      }
    })
}

export function updateProfile(form) {
  return request.post('/api/sys/manager/profile', form)
    .then(json => {
      if (json.result) {
        return json.data
      } else {
        return new Error(json.message)
      }
    })
}

export function changePassword(oldPassword, newPassword) {
  return request({
    method: 'post',
    url: '/api/sys/manager/changePassword',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    data: qs.stringify({oldPassword, newPassword})
  }).then(json => {
    if (json.result) {
      return json.data
    } else {
      return new Error(json.message)
    }
  })
}
